// 参考文档： 
// https://juejin.cn/post/7195124289501134905
// https://juejin.cn/post/7195124289501134905
// https://blog.csdn.net/qq_44416706/article/details/131002692
// https://zhuanlan.zhihu.com/p/338919198
// https://www.jianshu.com/p/96a4ab4d1675

import React from 'react'
import ReactQuill, { Quill } from 'react-quill';
import 'react-quill/dist/quill.snow.css';

interface IProps {
  value?: string
  placeholder?: string
  modules?: object
  formats?: any
  onChange?: (content: any, delta: any, source: any, editor: any) => void // content:内容、delta:变化、source:来源、editor:编辑器对象(包含各种获取方法)
  onChangeSelection?: (range: any, source: any, editor: any) => void
}

let fontFamily = ['宋体', '黑体', '微软雅黑', '楷体', '仿宋', 'Arial', '苹方'];
const font = Quill.import('formats/font');
font.whitelist = fontFamily;
// Quill.register(font, true);

const modules = {
  toolbar: {
    container: [
      ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
      ['blockquote', 'code-block'], // 引用，代码块
      [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
      [{ list: 'ordered' }, { list: 'bullet' }], // 列表
      [{ script: 'sub' }, { script: 'super' }], // 上下标
      [{ indent: '-1' }, { indent: '+1' }], // 缩进
      [{ direction: 'rtl' }], // 文本方向
      [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
      [{ header: [1, 2, 3, 4, 5, 6, false] }], // 几级标题
      [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
      [{ font: fontFamily }], // 字体
      [{ align: [] }], // 对齐方式
      ['clean'], // 清除字体样式
      ['image', 'video'], // 上传图片、上传视频
    ],
    imageResize: {
      // 调整图片尺寸
      displayStyles: {
        border: 'none',
      },
      modules: ['Resize', 'DisplaySize', 'Toolbar'],
    }
  },
}

const defaultProps = {
  value: '',
  placeholder: '请输入内容'
}

const RichTextEditor = (props: IProps, ref: any) => {
  props = { ...props, ...defaultProps }
  const [value, setValueState] = React.useState(props.value);
  const quillRef = React.createRef<ReactQuill>();

  const onChange = (content: any, delta: any, source: any, editor: any) => {
    // console.log('content', content)
    // console.log('delta', delta)
    // console.log('source', source)
    // console.log('editor', editor)
    setValueState(content)
    props.onChange && props.onChange(content, delta, source, editor)
  }

  React.useImperativeHandle(ref, () => ({
    getValue: () => value,
    setValue: (newValue: string) => setValueState(newValue),
    focus: () => quillRef.current?.focus(),
    blur: () => quillRef.current?.blur(),
    getEditor: () => quillRef.current?.getEditor()
  }))
  
  return (
    <>
      <ReactQuill
        ref={quillRef}
        value={ value }
        modules={ modules }
        className='rich-text-editor'
        theme='snow'
        onChange={ onChange }
        placeholder={ props.placeholder }
      />
    </>

  )
}

export default React.forwardRef(RichTextEditor)
